import {mAddProDevice, mDisBindDev, mSelectDevListByPage} from '@/api/device'
import useGlobalAPI from '@/hooks/useGlobalAPI'
import {FormInstance} from 'ant-design-vue'
import {PropType} from 'vue'
import DeviceInfoDrawer from '@/components/drawer/deviceInfoDrawer'
import {CoustomTableFn} from '@/components/table'
import {time2str} from '@/libs/date'
import {message, Modal} from '@/libs/global/antDesignVue'
import DeviceConConfDrawer from '@/components/drawer/deviceConConfDrawer'
import {CnMediumSpan} from '@/components/text'
import {getStorage} from '@/libs/localstoreage'
import DevTypeSelect from '@/components/select/devTypeSelect'
import { CreateDate } from '@/components/date'

/**设备列表 状态数据 */
interface Device_list_state {
  /**所有设备状态 */
  device_status_list: {label: string; value: string}[]
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: 'addProdDev' | 'editUploadInterval' | null
    /**弹窗 标题*/
    title: string
    /**宽度 */
    width: number | string
    /**添加生产设备 数据源 */
    addProDev_source: {
      devDesc: string
      devGId: string
      operateUser: string
    }
    // /**修改设备采集频率 */
    // editUploadInterval_source: {
    //   devGId: DevGId
    //   intervalData: string
    // }
  }
  table: CTable<Device.DataSource>
  search: {
    devGId: string | undefined
    devName: string | undefined
    devStatusCode: string | undefined
    devTypeId: string | undefined
    userCompany: string | undefined
    userPhone: string | undefined
  }
}

export let device_list_state = reactive<Device_list_state>({
  device_status_list: [
    {label: '在线', value: '0184'},
    {label: '离线', value: '0185'},
  ],
  modal: {
    visible: false,
    type: null,
    title: '',
    width: 520,
    addProDev_source: {
      devDesc: '',
      devGId: '',
      operateUser: '',
    },
  },
  table: {
    dataSource: [],
    loading: false,
    pagination: {
      page: 1,
      size: 20,
    },
    onPaginatiChange: ({page, size}) => {
      let {pagination} = toRefs(device_list_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    },
    total: 0,
  },
  search: {
    devGId: '',
    devName: '',
    devStatusCode: undefined,
    devTypeId: undefined,
    userCompany: '',
    userPhone: '',
  },
})

/**获取表格数据 */
export async function getTableDatas() {
  let {dataSource, total: tableTotal, loading} = toRefs(device_list_state.table)
  let {devGId, devName, devStatusCode, devTypeId, userCompany, userPhone} =
    toRefs(device_list_state.search)
  let {page, size} = toRefs(device_list_state.table.pagination)
  let defaultData = {
    page: page.value,
    size: size.value,
    devGId: devGId.value || undefined,
    devName: devName.value || undefined,
    devStatusCode: devStatusCode.value || undefined,
    devTypeId: devTypeId.value || undefined,
    userCompany: userCompany.value || undefined,
    userPhone: userPhone.value || undefined,
  }
  loading.value = true
  let res = await mSelectDevListByPage(defaultData).catch(err => {})
  if (res) {
    let {list, total} = res.data
    dataSource.value = list
    tableTotal.value = total
  }
  loading.value = false
}

/**下拉选择输入关键字筛选 */
const filterOption = (input: string, option: any, target?: string) => {
  return (
    option[target || 'label'].toLowerCase().indexOf(input.toLowerCase()) >= 0
  )
}

//? 复用组件区 -----------------------------------

//? 页面组件区 -----------------------------------

/**设备列表 左侧搜索 筛选区域 */
export const ViewLeftFilter = defineComponent({
  name: 'ViewLeftFilter',
  setup(props, {emit}) {
    let {device_status_list, search} = toRefs(device_list_state)
    let formRef = ref<FormInstance>()

    watch(
      () => search.value.devTypeId,
      n => {
        refreshTable()
      }
    )
    watch(
      () => search.value.devStatusCode,
      n => {
        refreshTable()
      }
    )

    /**提交表单且数据验证成功后回调事件 */
    const handle_viewLeftFilter_form_finish = async () => {
      console.log(search.value)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_viewLeftFilter_form_finish_failed = () => {
      console.log('handle_form_finish_failed', search.value)
      viewLeftFilter_returnEmit()
    }

    /**表单 重置按钮 点击 */
    const handle_viewLeftFilter_form_reset = () => {
      viewLeftFilter_returnEmit()
      refreshTable()
    }

    // 清空表单 关闭外层弹框
    const viewLeftFilter_returnEmit = () => {
      formRef.value?.resetFields()
      search.value.devGId = undefined
      search.value.devName = undefined
      search.value.devStatusCode = undefined
      search.value.devTypeId = undefined
      search.value.userCompany = undefined
      search.value.userPhone = undefined
    }

    const handle_viewLeftFilter_form_item_enter = (event: any) => {
      if (event.key === 'Enter') {
        refreshTable()
      }
    }

    function refreshTable() {
      let {page, size} = toRefs(device_list_state.table.pagination)
      page.value = 1
      size.value = 20
      getTableDatas()
    }

    return () => (
      <a-form
        class="h-full viewLeftFilter overflow-auto relative"
        v-model={[formRef, 'ref']}
        name="addSysdictType"
        model={search.value}
        label-col={{span: 0}}
        wrapper-col={{span: 24}}
        onFinish={handle_viewLeftFilter_form_finish}
        onFinishFailed={handle_viewLeftFilter_form_finish_failed}
      >
        <a-form-item name="devName" class="mx-8 my-16">
          <a-input
            v-model={[search.value.devName, 'value']}
            placeholder="输入设备名称"
            allowClear
            onKeyup={(event: any) =>
              handle_viewLeftFilter_form_item_enter(event)
            }
          >
            {{
              prefix: () => (
                <i class="iconfont icon-shebeixinxi text-primary"></i>
              ),
            }}
          </a-input>
        </a-form-item>
        <a-form-item name="devGId" class="mx-8 my-16">
          <a-input
            v-model={[search.value.devGId, 'value']}
            placeholder="输入序列号"
            allowClear
            onKeyup={(event: any) =>
              handle_viewLeftFilter_form_item_enter(event)
            }
          >
            {{
              prefix: () => (
                <i class="iconfont icon-tiaoxingma text-primary"></i>
              ),
            }}
          </a-input>
        </a-form-item>

        <a-form-item name="userPhone" class="mx-8 my-16">
          <a-input
            v-model={[search.value.userPhone, 'value']}
            placeholder="输入用户手机号"
            allowClear
            onKeyup={(event: any) =>
              handle_viewLeftFilter_form_item_enter(event)
            }
          >
            {{
              prefix: () => (
                <i class="iconfont icon-shoujihao text-primary"></i>
              ),
            }}
          </a-input>
        </a-form-item>
        <a-form-item name="userCompany" class="mx-8 my-16">
          <a-input
            v-model={[search.value.userCompany, 'value']}
            placeholder="输入用户公司名称"
            allowClear
            onKeyup={(event: any) =>
              handle_viewLeftFilter_form_item_enter(event)
            }
          >
            {{
              prefix: () => (
                <i class="iconfont icon-gongsimingcheng1 text-primary"></i>
              ),
            }}
          </a-input>
        </a-form-item>
        <a-form-item name="devTypeId" class="mx-8 my-16">
          <DevTypeSelect
            v-model={[search.value.devTypeId, 'devTypeId']}
          ></DevTypeSelect>
          {/* <a-select
            v-model={[search.value.devTypeId, 'value']}
            options={selectDevTypeList.value}
            fieldNames={{
              label: 'devTypeName',
              value: 'devTypeId',
            }}
            allow-clear={true}
            show-search
            placeholder="选择设备型号"
            filter-option={(input: string, option: SysDict.Item) =>
              filterOption(input, option, 'devTypeName')
            }
          >
            {{
              suffixIcon: () => (
                <i class="iconfont icon-shebeixinghao text-primary"></i>
              ),
            }}
          </a-select> */}
        </a-form-item>

        <a-form-item name="devStatus" class="mx-8 my-16">
          <a-select
            v-model={[search.value.devStatusCode, 'value']}
            options={device_status_list.value}
            placeholder="选择设备状态"
            show-search
            allow-clear={true}
            filter-option={(input: string, option: any) =>
              filterOption(input, option)
            }
          >
            {{
              suffixIcon: () => (
                <i class="iconfont icon-zhuangtai text-primary"></i>
              ),
            }}
          </a-select>
        </a-form-item>

        <div class="w-full h-mainViewfooter absolute left-0 bottom-0 m-0 px-4 border-t border-default flex justify-end items-center">
          <a-button type="primary" onClick={handle_viewLeftFilter_form_reset}>
            重置
          </a-button>
          <a-button class="ml-4 " type="primary" onClick={refreshTable}>
            查询
          </a-button>
        </div>
      </a-form>
    )
  },
})

// /**设备列表 表格 */
// const DeviceTable = CoustomTableFn<Device.DataSource>()
// export const DeviceListTable = defineComponent({
//   setup(props) {
//     let {dataSource, total, loading} = toRefs(device_list_state.table)
//     let {page, size} = toRefs(device_list_state.table.pagination)
//     let columns = [
//       {
//         title: '设备编号',
//         dataIndex: 'devId',
//         ellipsis: true,
//         width: 100,
//       },
//       {
//         title: '设备名称',
//         dataIndex: 'devName',
//         ellipsis: true,
//       },
//       {
//         title: '设备型号',
//         dataIndex: 'devTypeId',
//         ellipsis: true,
//         width: 120,
//       },
//       {
//         title: '序列号',
//         dataIndex: 'devGId',
//         ellipsis: true,
//         width: 200,
//       },
//       {
//         title: '设备状态',
//         dataIndex: 'devStatus',
//         ellipsis: true,
//         width: 100,
//       },
//       {
//         title: '是否绑定',
//         dataIndex: 'isBind',
//         ellipsis: true,
//         width: 120,
//       },
//       {
//         title: '创建时间',
//         dataIndex: 'devCreateTime',
//         ellipsis: true,
//         width: 180,
//       },
//       {
//         title: '操作',
//         isUtil: true,
//         width: 180,
//       },
//     ]
//     return () => (
//       <DeviceTable
//         class="h-full"
//         dataSource={dataSource.value}
//         loading={loading.value}
//         rowKey="devId"
//         columns={columns}
//         pagination={{
//           page: page.value,
//           size: size.value,
//           total: total.value,
//         }}
//       >
//         {{
//           util: (record: Device.DataSource) => (
//             <TypeHandleBtn record={record}></TypeHandleBtn>
//           ),
//         }}
//       </DeviceTable>
//     )
//   },
// })

/**设备列表 表格上方操作栏 */
export const TypeMainViewNav = defineComponent({
  setup() {
    let {router} = useGlobalAPI()
    let {visible, type, title} = toRefs(device_list_state.modal)
    const handle_add_prodDev_btn_click = () => {
      visible.value = true
      type.value = 'addProdDev'
      title.value = '添加生产设备'
    }

    return () => (
      <div class="w-full h-mainViewNav border-b border-default bg-white px-4 flex justify-end items-center">
        <a-button
          type="primary"
          class="mr-4"
          onClick={handle_add_prodDev_btn_click}
        >
          添加设备
        </a-button>
      </div>
    )
  },
})

/**设备列表 表格 操作栏 */
export const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<Device.DataSource>,
      default: {},
    },
  },
  setup(props) {
    let {router} = useGlobalAPI()
    // let {visible, title, type, width} = toRefs(device_list_state.modal)
    type MenuKey =
      | 'editUploadInterval'
      | 'routerToCheckHistory'
      | 'debug'
      | 'disBindDev'
      | 'showDevMsg'
    const onContextMenuClick = async (menuKey: MenuKey) => {
      switch (menuKey) {
        // case 'editUploadInterval':
        //   getUSelectDevUploadInterval(props.record.devGId)
        //   title.value = `修改${props.record.devName}的采集频率`
        //   type.value = 'editUploadInterval'
        //   visible.value = true
        //   break
        case 'routerToCheckHistory':
          router.push({
            path: '/device/list/checkHistory',
            query: {
              devId: props.record.devId,
              devName: props.record.devName,
            },
          })
          break
        case 'debug':
          router.push({
            path: '/device/list/debug',
            query: {
              devGId: props.record.devGId,
            },
          })
          break
        case 'disBindDev':
          if (props.record.isBind == 1) {
            let userId = getStorage('userId')
            if (userId) {
              Modal.confirm({
                title: '是否解绑此设备？',
                content: '所属用户手机号为：' + props.record.userPhone,
                onOk() {
                  mDisBindDev({
                    platFormUserId: userId,
                    devId: props.record.devId,
                  })
                    .then(res => {})
                    .catch(err => {})
                },
              })
            } else {
              message.warning('该设备暂未被绑定！')
            }
          }
          break
      }
    }
    return () => (
      <div class="flex items-center gap-x-6">
        <DeviceInfoDrawer
          devGId={props.record.devGId}
          devId={props.record.devId}
          class="h-full mr-2 text-primary pb-0.5 border-b cursor-pointer"
        ></DeviceInfoDrawer>

        <DeviceConConfDrawer
          devId={props.record.devId}
          devName={props.record.devName}
          class="h-full mr-2 text-primary pb-0.5 border-b cursor-pointer"
        ></DeviceConConfDrawer>
        <a-dropdown trigger={['click']}>
          {{
            default: () => (
              <span class="mr-2 text-primary pb-0.5 border-b cursor-pointer">
                更多功能
              </span>
            ),
            overlay: () => (
              <a-menu
                onClick={({key}: {key: MenuKey}) => onContextMenuClick(key)}
              >
                {/* <a-menu-item key="editUploadInterval">
                  <TableUtilBtn>修改采集频率</TableUtilBtn>
                </a-menu-item> */}
                <a-menu-item key="routerToCheckHistory">
                  <span class="mr-2 text-primary border-b cursor-pointer">
                    历史记录
                  </span>
                </a-menu-item>
                <a-menu-item key="debug">
                  <span class="mr-2 text-primary border-b cursor-pointer">
                    调试
                  </span>
                </a-menu-item>
                <a-menu-item key="disBindDev">
                  <span class="mr-2 text-danger border-b cursor-pointer">
                    解绑
                  </span>
                </a-menu-item>
              </a-menu>
            ),
          }}
        </a-dropdown>
      </div>
    )
  },
})

/**设备列表 表格 */
const CoustomTable = CoustomTableFn<Device.DataSource>()
export const DeviceListTable = defineComponent({
  setup(props) {
    let {dataSource, total, loading, onPaginatiChange} = toRefs(
      device_list_state.table
    )
    let {page, size} = toRefs(device_list_state.table.pagination)
    let columns: CColumn<Device.DataSource>[] = [
      {
        title: '设备序号',
        dataIndex: 'devId',
        ellipsis: true,
        width: 100,
      },
      {
        title: '设备名称',
        dataIndex: 'devName',
        ellipsis: true,
      },
      {
        title: '设备序列号',
        dataIndex: 'devGId',
        ellipsis: true,
      },
      {
        title: '设备型号',
        dataIndex: 'devTypeName',
        ellipsis: true,
      },
      {
        title: '设备状态',
        dataIndex: 'devStatus',
        ellipsis: true,
        width: 100,
      },
      {
        title: '是否绑定',
        dataIndex: 'isBind',
        ellipsis: true,
        width: 120,
        customRender({column, text}) {
          return text == '0' ? '否' : text == '1' ? '是' : '---'
        },
      },
      {
        title: '创建时间',
        dataIndex: 'devCreateTime',
        ellipsis: true,
        width:160,
        customRender({column, text}) {
          return <CreateDate date={text}></CreateDate>
        },
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true,
        width: 240,
        customRender({record}) {
          return <TypeHandleBtn record={record}></TypeHandleBtn>
        },
      },
    ]
    return () => (
      <CoustomTable
        class="h-full"
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey="devGId"
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value,
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
        isDefaultBodyCell={false}
      ></CoustomTable>
    )
  },
})

/**生产设备添加 表单 添加用 */
const AddProdDeviceForm = defineComponent({
  name: 'AddProdDeviceForm',
  emits: ['finish'],
  setup(props, {emit}) {
    let {addProDev_source} = toRefs(device_list_state.modal)

    let formRef = ref<FormInstance>()

    let onLoading = ref(false)

    let userId = computed(() => store.getters['login/GETPLATFORMUSERID'])

    let {store} = useGlobalAPI()

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      onLoading.value = true
      addProDev_source.value.operateUser = userId.value || ''
      await mAddProDevice(addProDev_source.value).catch(err => {})
      setTimeout(() => {
        onLoading.value = false
        returnEmit()
      }, 300)
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', addProDev_source.value)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name="addDeviceTypeDatasForm"
        model={addProDev_source.value}
        label-col={{span: 4}}
        wrapper-col={{span: 16}}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label="序列号" name="devGId">
          <a-input v-model={[addProDev_source.value.devGId, 'value']}></a-input>
        </a-form-item>
        <a-form-item label="备注" name="devDesc">
          <a-input
            v-model={[addProDev_source.value.devDesc, 'value']}
          ></a-input>
        </a-form-item>
        <a-form-item>
          <a-button
            type="primary"
            class="float-right mx-4"
            html-type="submit"
            loading={onLoading.value}
          >
            提交
          </a-button>
          <a-button class="float-right mx-4" onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  },
})

/**设备列表 弹窗 */
export const TypeModel = defineComponent({
  setup(props, {emit}) {
    let {visible, type, title, width} = toRefs(device_list_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = null
      width.value = 520
      getTableDatas()
    }
    return () => {
      let dynamicCom = <div></div>
      let footer = null
      switch (type.value) {
        case 'addProdDev':
          dynamicCom = (
            <AddProdDeviceForm
              onFinish={handle_form_finish}
            ></AddProdDeviceForm>
          )
          break
        // case 'editUploadInterval':
        //   dynamicCom = (
        //     <EditUploadIntervalForm
        //       onFinish={handle_form_finish}
        //     ></EditUploadIntervalForm>
        //   )
        //   break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          width={width.value}
          onCancel={() => {
            handle_form_finish()
          }}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  },
})
